package com.hongkou.tvstation.common.taglib.warning;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.hongkou.tvstation.common.action.MultiWarning;

public class WarningTag extends TagSupport {
	private MultiWarning multiWarning;

	public MultiWarning getMultiWarning() {
		return multiWarning;
	}

	public void setMultiWarning(MultiWarning multiWarning) {
		this.multiWarning = multiWarning;
	}

	public int doStartTag() throws JspException {
		JspWriter out = this.pageContext.getOut();
		if (multiWarning == null)
			return EVAL_BODY_INCLUDE;
		try {
			String trTable = "<tr><td>{0}</td><td>{1}</td></tr>";
			StringBuffer errorMessage = new StringBuffer();
			StringBuffer continueButton = new StringBuffer();
			String html = null;
			for (String message : multiWarning.getWarning()) {
				errorMessage.append("<p class=error_message>" + message
						+ "</p>");
			}

			if (multiWarning.isContinueable()) {
				HttpServletRequest request = (HttpServletRequest) pageContext
						.getRequest();
				Map param = request.getParameterMap();
				continueButton.append(request.getRequestURL());
				continueButton.append("?1=1");
				Set key = param.keySet();
				Iterator iterator = key.iterator();
				while (iterator.hasNext()) {
					String name = (String) iterator.next();
					continueButton.append("&");
					String value = request.getParameter(name);
					continueButton.append(name + "=" + value);
				}
			}
			html = MessageFormat.format(trTable, errorMessage.toString(),
					continueButton);
			out.println(html);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return EVAL_BODY_INCLUDE;
	}
}
